<template>
    <div :class="`tech-shop-order-detail ${mode}`">
        <OrderStatusInfo :statusInfo="statusInfo" :orderInfo="orderDetail" @orderCancel="cancelAction" @orderRefund="refundOrder" :mode="mode" />
        <SelfPickUpInfo v-if="statusInfo.isPickUp && isShowPickUpInfo" :name="orderDetail.warehouse_name" :info="orderDetail.pick_up_info" :bookTime="orderDetail.booking_valid_time" :mode="mode" :theme="theme" :styleMode="styleMode" />
        <AddressInfo v-if="statusInfo.isExpress || statusInfo.isDayExpress" :info="orderDetail.address_info" :mode="mode" />
        <DayExpressInfo v-if="statusInfo.isDayExpress && orderDetail.booking_valid_time" :day="orderDetail.booking_valid_time" :mode="mode" />
        <TechPanel :title="orderDetail.warehouse_name" no-padding :isBold="true" :mode="mode">
            <OrderDetailGoodsItem
                v-for="(item, index) in orderDetail.details"
                :key="index"
                :itemInfo="item"
                :isHaveAfterSale="statusInfo.isHaveAfterSale"
                :mode="mode"
                :theme="theme"
                :styleMode="styleMode"
                @afterSale="dealAfterSale"
            />
            <OrderDiscount :discountList="orderDetail.discounts" :deliveryPrice="orderDetail.delivery_fee" :mode="mode" />
            <OrderTotalPrice label="合计" :isHaveBorder="true" :discountPrice="orderDetail.discount / 100" :totalPrice="orderDetail.trans / 100" :mode="mode" />
        </TechPanel>
        <OrderBaseInfo :info="orderDetail" :mode="mode" />
        <!-- <ContactService :mode="mode" :styleMode="styleMode" /> -->
        <OrderDetailActionBar
            v-if="statusInfo.isHaveActionBar"
            :statusInfo="statusInfo"
            :price="orderDetail.trans"
            :discountPrice="orderDetail.discount"
            :mode="mode"
            :theme="theme"
            :styleMode="styleMode"
            @receivi="receiviOrder"
            @pay="payAction"
        />
        <!-- 无法售后提示 -->
        <TechDialog
            ref="afterSale"
            title="无法申请退款"
            :content="`您已超过申请退款的时间段（订单签收后${orderDetail.refund_allowed_days || 7}天内），请联系客服申请`"
            okText="我知道了"
            :haveCancel="false"
            :mode="mode"
            :theme="theme"
            :styleMode="styleMode"
            container="body"
        />
        <!-- 组合单提示 -->
        <UniteOrderTip ref="tip" :uniteOrderInfo="uniteOrderInfo" @cancel="cancelOrder" @pay="payOrder" :isCancel="isCancel" :mode="mode" :styleMode="styleMode" :theme="theme" />
        <!-- 支付方式 -->
        <ShopPayType ref="paytype" @ensure="orderPayAction" />
        <!-- 密码认证 -->
        <ShopMemberPassword ref="authModal" @ensure="authPasswordResult" :mode="mode" :theme="theme" :styleMode="styleMode" />
    </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { TechPanel, TechDialog } from '@components/base';
import OrderStatusInfo from './orderDetail/OrderStatusInfo';
import AddressInfo from './orderDetail/AddressInfo';
import SelfPickUpInfo from './orderDetail/SelfPickUpInfo';
import DayExpressInfo from './orderDetail/DayExpressInfo';
import OrderDetailGoodsItem from './orderDetail/OrderDetailGoodsItem';
import OrderDiscount from './orderDetail/OrderDiscount';
import OrderBaseInfo from './orderDetail/OrderBaseInfo';
import ContactService from './orderDetail/ContactService';
import OrderDetailActionBar from './orderDetail/OrderDetailActionBar';
import OrderTotalPrice from './orderDetail/OrderTotalPrice';
import UniteOrderTip from './components/UniteOrderTip';
import ShopPayType from './components/ShopPayType';
import ShopMemberPassword from './components/ShopMemberPassword';

import { SHOP_TRADE_CHANNEL } from '@constants/shop';
import { getShopOrderTipInfo } from '@biztools/shopOrder';
import { autoShopPayment } from '@common/environment';
import { setTitle, compareTime, redirectTo, isEmptyObject } from '@common/utils';
import { getUiMode, getUiTheme, getUiStyleMode } from '@biztools/info';
import { DEFAULT_MODE, DEFAULT_THEME, DEFAULT_STYLE_MODE } from '@constants/style';
import { PAY_TYPE_MEMBERCARD, PAY_TYPE_WECHAT, PAY_TYPE_ALIPAY, SHOP_ORDER_PAY_TYPE_VALUE } from '@constants/pay';
import logger from '@common/logger';
import { ClearTip, TipError, TipLoading, TipSuccess } from '@common/tip';

export default {
    name: 'ShopOrderDetail',
    components: {
        TechPanel,
        TechDialog,
        OrderTotalPrice,
        OrderStatusInfo,
        AddressInfo,
        SelfPickUpInfo,
        DayExpressInfo,
        OrderDetailGoodsItem,
        OrderDiscount,
        OrderBaseInfo,
        ContactService,
        OrderDetailActionBar,
        UniteOrderTip,
        ShopPayType,
        ShopMemberPassword,
    },
    data() {
        return {
            uniteOrderInfo: {},
            isCancel: false,
            // 获取设置的配置信息
            mode: getUiMode() || DEFAULT_MODE,
            theme: getUiTheme() || DEFAULT_THEME,
            styleMode: getUiStyleMode() || DEFAULT_STYLE_MODE,
        };
    },
    async created() {
        setTitle('订单详情');
        TipLoading('加载中...');
        const { orderNumber } = this.$route.params;
        logger.info('OrderDetail => 订单号为：', orderNumber);
        await this.getShopOrderDetail(orderNumber);
        // 获取用户信息
        // await this.getShopMemberInfo();
        ClearTip();
    },
    computed: {
        ...mapState({
            orderDetail: state => state.shopOrder.orderDetail,
            memberInfo: state => state.shopMember.memberInfo,
        }),
        statusInfo() {
            logger.info('订单状态处理结果 ==> ', getShopOrderTipInfo(this.orderDetail || {}));
            return getShopOrderTipInfo(this.orderDetail || {});
        },
        // 是否是模板消息跳转的订单详情
        isTemplateLink() {
            const { isLink } = this.$route.query;
            return isLink && isLink === 'true';
        },
        isShowPickUpInfo() {
            const { pick_up_info={} } = this.orderDetail;
            return !isEmptyObject(pick_up_info);
        },
    },
    methods: {
        ...mapActions([
            'getShopMemberInfo',
            'getShopOrderDetail',
            'confirmShopOrder',
            'getUniteOrderAbstract',
            'directCancelUniteOrder',
            'cancelUniteOrder',
            'repayUniteOrderAction',
            'virtualOrderAction',
            'setAfterSaleGoodsInfo', // 设置售后
            'setAfterSaleOrderInfo', // 设置售后订单信息
        ]),
        // 处理售后事件
        dealAfterSale(info) {
            const { refund_deadline } = this.orderDetail;
            if (!refund_deadline || compareTime(refund_deadline)) {
                // 执行跳转售后页
                this.setAfterSaleOrderInfo(this.orderDetail);
                this.setAfterSaleGoodsInfo(info);
                this.$router.push('/shop-order/after-sale/select-type-item');
            } else {
                this.$refs.afterSale.show();
            }
        },
        // 整单申请退款
        refundOrder() {
            // 跳转到申请取消页面-整单
            this.setAfterSaleOrderInfo(this.orderDetail);
            logger.warn('跳转到申请整单取消');
            redirectTo('shop-order/cancel');
        },
        // 确认收货
        async receiviOrder() {
            const { orderNumber } = this.$route.params;
            const flag = await this.confirmShopOrder(orderNumber);
            flag ? TipSuccess('确认成功！') : TipError('确认失败，请重试！');
        },
        async showTipAction(isCancel=false) {
            const info = await this.getUniteOrderAbstract(this.orderDetail.request_id);
            this.uniteOrderInfo = info;
            this.isCancel = isCancel;
            this.$refs.tip.show();
        },
        // 取消订单
        async cancelAction() {
            logger.warn('取消订单');
            await this.showTipAction(true);
        },
        // 订单支付
        async payAction() {
            await this.showTipAction(false);
        },
        // 取消订单
        async cancelOrder() {
            if (this.statusInfo.isDirectCancel) {
                // 直接取消
                await this.directCancelUniteOrder(this.orderDetail.request_id);
            } else {
                // 取消同事删除预支付单
                await this.cancelUniteOrder(this.orderDetail.request_id);
            }
        },
        // 支付订单
        async payOrder() {
            logger.info('商城订单支付');
            if (this.uniteOrderInfo.pay_method) {
                await this.orderPayAction(this.uniteOrderInfo.pay_method);
            } else {
                this.$refs.paytype.show();
            }
        },
        async orderPayAction(paytype) {
            // 判断是否是免密
            if (!this.memberInfo.openNosecret && paytype === SHOP_ORDER_PAY_TYPE_VALUE[PAY_TYPE_MEMBERCARD]) {
                logger.success('OrderListItem => 开始认证密码');
                // 打开密码框
                this.$refs.authModal.show();
            } else {
                await this.payAction(paytype);
            }
        },
        async authPasswordResult(flag) {
            if (flag) {
                await this.payAction(SHOP_ORDER_PAY_TYPE_VALUE[PAY_TYPE_MEMBERCARD]);
            }
        },
        async payActionRun(paytype) {
            const param = {
                biz_request_no: this.orderDetail.request_id,
                pay_method: paytype,
                trade_channel: SHOP_TRADE_CHANNEL,
            };
            const info = await this.repayUniteOrderAction(param);
            if (info.status === 1) {
                TipSuccess('支付成功！');
                await this.getShopOrderDetail(this.orderDetail.order_number);
            } else {
                autoShopPayment(info.prepay_info, this.orderDetail.order_number, async (flag, type) => {
                    // 处理支付结果
                    if (flag) {
                        TipSuccess('支付成功！');
                        await this.virtualOrderAction(info.pay_order_number);
                        await this.getShopOrderDetail(this.orderDetail.order_number);
                    } else {
                        TipError('支付失败，请重试！');
                    }
                });
            }
        },
    },
};
</script>

<style lang="less">
.tech-shop-order-detail {
    .mode-white();
    .p-v(@shop-gap-md);
    .p-b(80);
    &.white {
        background-color: @shop-bg-color;
    }
    &.black {
        background-color: #000000;
    }
}
</style>
